import {
    HEADER,
    CACHE_TOKEN,
    HTTP_REQUEST_URL
} from './../config.js';
import {
    getReLogin,

} from "../api/index.js"
const md5 = require('./md5code.js');

const signatureProcess = (data) => {
    let keys = Object.keys(data).sort()
    let query = keys.map(key => {
        return `${key}=${data[key]}`
    }).join('&')
    let signStr = md5.hexMD5(query).toUpperCase() + "code=MrRRC&"
    let signFinal = md5.hexMD5(signStr).toUpperCase()
    return signFinal
}

const base64_decode = (input) => { // 解码，配合decodeURIComponent使用
    var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
    while (i < input.length) {
        enc1 = base64EncodeChars.indexOf(input.charAt(i++));
        enc2 = base64EncodeChars.indexOf(input.charAt(i++));
        enc3 = base64EncodeChars.indexOf(input.charAt(i++));
        enc4 = base64EncodeChars.indexOf(input.charAt(i++));
        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;
        output = output + String.fromCharCode(chr1);
        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }
    }
    return (output);
}

/**
 * 发送请求
 */
/**
 * 发送请求
 */
export default function request(url, param, callback) {
    console.log('发送请求：', url, param);

    const commonParams = {
        sys_type: 'app',
        version_name: '6.16.0',
        client_device: 'wechat_xcx',
        timestamp: parseInt(Date.now() / 1000),
        token: wx.getStorageSync(CACHE_TOKEN)
    }
    const sendParams = Object.assign(commonParams, param.data)
    sendParams['sign'] = signatureProcess(sendParams)
    return new Promise((resolve, reject) => {
        wx.request({
            url: HTTP_REQUEST_URL + url,
            method: param.method || 'GET',
            header: {
                'content-type': 'application/x-www-form-urlencoded',
                // token: "eyJpc19sb2NrIjoiMCIsInI"
            },
            data: sendParams,
            success: (res) => {
               
                if (res.data.result == 0) {
                    res.data.data = JSON.parse(base64_decode(res.data.data))
                    resolve(res.data.data);
                    callback && callback(null, res.data.data);
                } else if (res.data.result == 101 && res.data.msg == 'token不存在') {
                    wx.reLaunch({
                        url: '/pages/login/index',
                    })
                } else if (res.data.result == 301) {
                    console.log('1token已过期，重新刷新登录接口', res.data.result);
                    wx.reLaunch({
                        url: '/pages/login/index',
                    })
                    // let data = { || res.data.result == 101
                    //     act: 'login',
                    //     sys_type: 'app',
                    //     phone: '17776642313',// 15600000000 18172060066
                    //     password: '123456',
                    //     client_device: 'wechat_xcx'
                    // }
                    // getReLogin(data).then(res => {
                    //     console.log('返回', res)
                    //     // 修改全局变量中的数据
                    //     wx.setStorageSync('TOKEN', res.token);
                    //     resolve(res.data);
                    //     callback && callback(null, res.data);
                    // })

                } else {
                    
                    resolve(res.data);
                    callback && callback(null, res.data); // 调用接口回调函数并传递请求结果
                }
            },
            fail: (err) => {
                
                reject(err);
                callback && callback(err, null); // 调用接口回调函数并传递错误信息
            }
        });
    });
}

/**
 * 发送请求
 */
export function requestFile(url, param, callback) {
    console.log('发送请求file：', url, param);

    const commonParams = {
        sys_type: 'app',
        version_name: '6.16.0',
        client_device: 'wechat_xcx',
        timestamp: parseInt(Date.now() / 1000),
        token: wx.getStorageSync(CACHE_TOKEN)
    }
    const sendParams = Object.assign(commonParams, param.data)
    sendParams['sign'] = signatureProcess(sendParams)
    return new Promise((resolve, reject) => {
        wx.request({
            url: HTTP_REQUEST_URL + url,
            method: param.method || 'GET',
            header: {
                'content-type': 'multipart/form-data',
                // token: "eyJpc19sb2NrIjoiMCIsInI"
            },
            data: sendParams,
            success: (res) => {

                if (res.data.result == 0) {
                    res.data.data = JSON.parse(base64_decode(res.data.data))
                    resolve(res.data.data);
                    callback && callback(null, res.data.data);
                } else if (res.data.result == 301 || res.data.result == 101) {
                    console.log('1token已过期，重新刷新登录接口', res.data.result);
                    wx.reLaunch({
                        url: '/pages/login/index',
                    })
                    // let data = {
                    //     act: 'login',
                    //     sys_type: 'app',
                    //     phone: '17776642313',// 15600000000
                    //     password: '123456',
                    //     client_device: 'wechat_xcx'
                    // }
                    // getReLogin(data).then(res => {
                    //     console.log('返回', res)
                    //     // 修改全局变量中的数据
                    //     wx.setStorageSync('TOKEN', res.token);
                    //     resolve(res.data);
                    //     callback && callback(null, res.data);
                    // })

                } else {
                    console.log('res', res)
                    resolve(res.data);
                    callback && callback(null, res.data); // 调用接口回调函数并传递请求结果
                }
            },
            fail: (err) => {

                reject(err);
                callback && callback(err, null); // 调用接口回调函数并传递错误信息
            }
        });
    });
}

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect', 'upload'].forEach((method) => {
    request[method] = (api, data, opt, callback) => {
        const token = opt && opt.token ? opt.token : '';
        return request(api, {
            method,
            data,
            token
        }, callback);
    };
});